<template>
  <q-modal v-model="modalVisible" :header="header" width="500" @beforeClose="handleClose" @confirm="handleSubmit">
    <qx-form ref="mapRef" v-model="mapForm" :option="mapOption"></qx-form>
  </q-modal>
</template>

<script setup>
import { i18n, toI18nName } from 'boot/i18n'
import { postAPI } from 'src/api'
import { setRemoteData } from 'src/enum/ajaxRemoteData.js'
import { mapDirections } from 'src/views/MapCore/enum.js'
import { computed, inject, ref, watch } from 'vue'

const props = defineProps({ mapInfo: { type: Object, default: () => ({}) }, mapCodes: Array })
const modalVisible = defineModel('modelValue', { type: Boolean, default: false })
const setSingleMaps = inject('setSingleMaps')

const mapForm = ref({})
const mapRef = ref(null)
const readonly = computed(() => !!mapForm.value.id)
const header = computed(() => readonly.value ? `${i18n.t('MapCore.EditMap')}` : `${i18n.t('MapCore.CreateNewMap')}`)
const mapOption = computed(() => {
  return {
    span: 22, labelWidth: 100,
    column: [{
      label: `${i18n.t('MapCore.MapName')}`, field: 'mapName', required: true
    }, {
      label: `${i18n.t('MapCore.MapAbbreviation')}`, field: 'mapAlias', required: true,
      tips: `${i18n.t('MapCore.MapAbbreviationTips')}`
    }, {
      label: `${i18n.t('MapCore.GroundCodeType')}`, field: 'mapGroundCode', type: readonly.value ? 'input' : 'select',
      required: true, options: props.mapCodes || [], props: { label: toI18nName('labelZhCn'), value: 'key' },
      readonly: readonly.value
    }, {
      label: `${i18n.t('MapCore.MapDirection')}`, field: 'mapAngle', type: 'radio', required: true, value: '0',
      options: mapDirections.value
    }]
  }
})
watch(modalVisible, value => value && (mapForm.value = { ...props.mapInfo }))
const handleClose = () => {
  if (mapRef.value) mapRef.value.onReset()
  modalVisible.value = false
}
const handleSubmit = mDone => {
  if (!mapRef.value) return mDone && mDone(false)
  mapRef.value.validate((form, done) => {
    const url = form.id ? '/yfagv/api/agvMap/updateAgvMapInfo' : '/yfagv/api/agvMap/saveAgvMapInfo'
    postAPI(url, form, data => {
      setRemoteData('agv_map')
      setSingleMaps && setSingleMaps(data)
      done()
      mDone && mDone()
    }, () => {
      done()
      mDone && mDone(false)
    })
  }, () => mDone && mDone(false))
}
</script>